// API 测试工具
import { makeRequest, runNetworkDiagnosis, NetworkConfig } from './networkConfig';

// 测试 API 连接
export async function testApiConnection() {
  console.log('=== 开始 API 连接测试 ===');
  
  try {
    // 测试彩票分类 API
    const classUrl = `${NetworkConfig.API_BASE_URL}/class?appkey=${NetworkConfig.API_KEY}`;
    console.log('测试 URL:', classUrl);
    
    const result = await makeRequest(classUrl);
    console.log('API 测试成功:', result);
    
    return {
      success: true,
      data: result,
      message: 'API 连接正常'
    };
    
  } catch (error) {
    console.error('API 测试失败:', error);
    
    return {
      success: false,
      error: error.message,
      suggestions: error.suggestions || [],
      environment: error.environment
    };
  }
}

// 运行完整诊断
export async function runFullDiagnosis() {
  console.log('=== 开始完整网络诊断 ===');
  
  const diagnosis = await runNetworkDiagnosis();
  const apiTest = await testApiConnection();
  
  const fullReport = {
    ...diagnosis,
    apiTest: apiTest,
    recommendations: []
  };
  
  // 生成建议
  if (!apiTest.success) {
    if (apiTest.error?.includes('CORS') || apiTest.error?.includes('跨域')) {
      fullReport.recommendations.push('启动开发服务器时确保代理配置生效');
      fullReport.recommendations.push('检查 setupProxy.js 文件是否正确');
    }
    
    if (apiTest.error?.includes('timeout') || apiTest.error?.includes('超时')) {
      fullReport.recommendations.push('检查网络连接速度');
      fullReport.recommendations.push('尝试增加超时时间');
    }
    
    if (apiTest.error?.includes('404') || apiTest.error?.includes('500')) {
      fullReport.recommendations.push('API 服务可能暂时不可用');
      fullReport.recommendations.push('考虑使用模拟数据进行开发');
    }
  }
  
  console.log('完整诊断报告:', fullReport);
  return fullReport;
}

// 显示诊断结果（如果在浏览器环境中）
export function showDiagnosisModal(diagnosis) {
  if (typeof window !== 'undefined' && window.Modal) {
    const content = `
      <div>
        <h4>诊断时间: ${new Date(diagnosis.timestamp).toLocaleString('zh-CN')}</h4>
        <p><strong>运行环境:</strong> ${diagnosis.environment}</p>
        
        <h4>测试结果:</h4>
        ${diagnosis.tests.map(test => `
          <div style="margin: 10px 0; padding: 10px; background: ${test.status === '成功' ? '#f6ffed' : '#fff2f0'}; border-radius: 4px;">
            <div style="font-weight: bold; color: ${test.status === '成功' ? '#52c41a' : '#ff4d4f'};">
              ${test.name}: ${test.status}
            </div>
            <div style="margin-top: 5px; color: #666;">
              ${test.message}
            </div>
            ${test.suggestions ? `
              <div style="margin-top: 5px; font-size: 12px; color: #1890ff;">
                建议: ${test.suggestions.join(', ')}
              </div>
            ` : ''}
          </div>
        `).join('')}
        
        <h4>API 测试:</h4>
        <div style="margin: 10px 0; padding: 10px; background: ${diagnosis.apiTest.success ? '#f6ffed' : '#fff2f0'}; border-radius: 4px;">
          <div style="font-weight: bold; color: ${diagnosis.apiTest.success ? '#52c41a' : '#ff4d4f'};">
            状态: ${diagnosis.apiTest.success ? '成功' : '失败'}
          </div>
          <div style="margin-top: 5px; color: #666;">
            ${diagnosis.apiTest.success ? diagnosis.apiTest.message : diagnosis.apiTest.error}
          </div>
        </div>
        
        ${diagnosis.recommendations.length > 0 ? `
          <h4>解决建议:</h4>
          <ul>
            ${diagnosis.recommendations.map(rec => `<li>${rec}</li>`).join('')}
          </ul>
        ` : ''}
      </div>
    `;
    
    window.Modal.info({
      title: '网络诊断报告',
      content: content,
      width: 800,
      okText: '确定'
    });
  } else {
    // 控制台输出
    console.log('=== 网络诊断报告 ===');
    console.table(diagnosis.tests);
    console.log('API 测试结果:', diagnosis.apiTest);
    if (diagnosis.recommendations.length > 0) {
      console.log('建议:', diagnosis.recommendations);
    }
  }
}